package com.shawn.spring.boot.redis.service.impl;

import com.shawn.spring.boot.redis.entity.CoffeeEntity;
import com.shawn.spring.boot.redis.entity.CoffeeOrderEntity;
import com.shawn.spring.boot.redis.entity.OrderState;
import com.shawn.spring.boot.redis.repository.CoffeeOrderRepository;
import com.shawn.spring.boot.redis.service.CoffeeOrderService;
import java.util.Arrays;
import javax.transaction.Transactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author shawn
 * @since 2020/9/4
 */
@Slf4j
@Service
@Transactional
public class CoffeeOrderServiceImpl implements CoffeeOrderService {

  @Autowired private CoffeeOrderRepository orderRepository;

  @Override
  public CoffeeOrderEntity createOrder(String customer, CoffeeEntity... coffee) {
    CoffeeOrderEntity order =
        CoffeeOrderEntity.builder()
            .customer(customer)
            .items(Arrays.asList(coffee))
            .state(OrderState.INIT)
            .build();
    CoffeeOrderEntity coffeeOrderEntity = orderRepository.save(order);
    log.info("New Order: {}", coffeeOrderEntity);
    return coffeeOrderEntity;
  }

  @Override
  public boolean updateState(CoffeeOrderEntity order, OrderState state) {
    if (state.compareTo(order.getState()) <= 0) {
      log.warn("Wrong State order: {}, {}", state, order.getState());
      return false;
    }
    order.setState(state);
    orderRepository.save(order);
    log.info("Updated Order: {}", order);
    return true;
  }
}
